<?php

namespace app\uapi\controller;


use app\admin\model\KnscyBanner;
use app\admin\model\KnscyMessage;
use app\admin\model\KnscyPages;
use app\admin\model\KnscyUserBind;
use app\admin\model\KnscyUserPeople;
use app\admin\model\KnscyUsers;
use app\common\controller\ApiController;
use app\common\service\CommonService;
use app\common\service\UserService;
use app\common\service\WeginService;
use think\facade\Db;


class Webfront extends ApiController
{
    /**
     *
     * 必须要前端提供openid 对应用户是公众号还是小程序的 用户
     * 在公众里面，能通过php 得到openid
     * 在小程序里面，openid是进入小程序就能获取到的；
     * @return array
     */
    public function bindMobile()
    {
        $rule = [
            'mobile|手机号' => 'required',
        ];
        $post = $this->request->post();
        $this->validate($rule, $post );

        $mobile = $post['mobile'];
        $code = $post['verycode'];

        $openid = WeginService::openid();
        $uniacid = WeginService::getUniacid();
        !$openid &&  $this->error( '参数不完整');


        if (!preg_match( '/1[3456789][0-9]{9}$/', $mobile)) {
            $this->error(  '手机号码格式错误') ;
        }

        //检查验证码
        load()->model('utility');
        $smsverifycode = sysconfig('company','smsverifycode');
        if( $smsverifycode == 1 ) {
            if (!code_verify($uniacid, $mobile, $code)) {
                //不刪除驗證碼，有可能是用戶輸入有誤，所以不刪除先
                //table('uni_verifycode')->where(array('receiver' => $mobile))->delete();
                $this->error('验证码错误');
            }
        }
        //检测是否绑定过
        $bind = KnscyUserBind::where('openid', $openid)
            ->where('uniacid', $uniacid)
            ->where('bind_type', $mobile)->find();
        if(empty($bind)){
            $user = KnscyUsers::create([
                'uniacid'=> $uniacid,
                'username'=>$openid,
                'head_img'=>"/addons/kbwdl_nickscenery/public/images/get_avatar.png",
                'mobile'=>$mobile,
                'nickname'=>'微信用户',
                'status'=>1,
            ]);
           $bind =  KnscyUserBind::create([
                'openid'=>$openid,
                'uniacid'=> $uniacid,
                'user_id'=> $user->id,
                'bind_type'=> $mobile,
                'token' => md5($openid.$mobile),
            ]);
            //发送站内消息
            KnscyMessage::create([
                'user_id'=> $user->id,
                'tag' => '系统站内消息通知',
                'content'=>str_replace('{user}', $user->mobile, sysconfig('company','welcome_msg') ?? '恭喜您注册成为本小程序会员！')
            ]);

        }else{
            $user = KnscyUsers::where('id', $bind->user_id)->find();
            if(!$user){
                $user = KnscyUsers::create([
                    'uniacid'=> $uniacid,
                    'username'=>$openid,
                    'mobile'=>$mobile,
                    'head_img'=>"/addons/kbwdl_nickscenery/public/images/get_avatar.png",
                    'nickname'=>'微信用户',
                    'status'=>1,
                ]);
                //发送站内消息
                KnscyMessage::create([
                    'user_id'=> $user->id,
                    'tag' => '系统站内消息通知',
                    'content'=> str_replace('{user}', $user->mobile, sysconfig('company','welcome_msg') ?? '恭喜您注册成为本小程序会员！'),
                ]);
            }
            $user->last_login_ip = request()->ip();
            $user->last_login_time = time();
            $user->save();
            $bind->user_id = $user->id;
            $bind->save();
        }
        //采用短信验证的时候优先手机号鉴别 客户唯一
        if(!$user){
            $this->error('绑定注册失败');
        }


        $this->success( 'success', ['token'=> $bind->token] );
    }

    /**
     * 通过微擎的短信接口发送短信验证码和记录到验证表
     * @return void
     */
    public function sendsms()
    {
        $openid = WeginService::openid();

        $mobile = $this->request->post('mobile');
        $uniacid = WeginService::getUniacid();
        /*
        */
        if(empty($openid)){
            $this->error( '参数错误');
        }
        if(empty($mobile)){
            $this->error(  '请输入手机号码');
        }
        if (!preg_match( '/1[3456789][0-9]{9}$/', $mobile)) {
            $this->error(  '手机号码格式不正确')  ;
        }
        //记录数据
        $verifycode_table = table('uni_verifycode');
        try{
            $row = $verifycode_table->getByReceiverVerifycode($uniacid, $mobile, '');
        }catch (\Exception $e){
            $row = null;
        }
        //生成随机数
        $numbers = range(1, 9);
        // 随机排列数组中的元素
        shuffle($numbers);
        $code = implode("", array_slice($numbers, 0, 6));

        $record = [
            'verifycode' => $code
        ];

        if (!empty($row)) {
            if ($row['total'] >= 3) {
                $this->error(   '您的操作过于频繁,请稍后再试');
            }
            $record['total'] = $row['total'] + 1;
            pdo_update('uni_verifycode', $record, array('id' => $row['id']));
        } else {
            $record['uniacid'] = $uniacid;
            $record['receiver'] = $mobile;
            $record['total'] = 1;
            $record['createtime'] = TIMESTAMP;
            pdo_insert('uni_verifycode', $record);
        }

        //发送
        load()->model('cloud');
        $prepare = cloud_prepare();
        if (is_error($prepare)) {
            $this->error(   $prepare['message']);
        }
        $postdata = array('verify_code' =>  $code);
        $result = cloud_sms_send($mobile, '800010', $postdata);
        if (is_error($result)) {
            $this->error(    $result['message'] );
        }
        $this->success( '短信发送成功!');
    }
    public function getphone()
    {
        global $_W, $_GPC;

        //解密失败，采用api接口获取
        /*获取小程序access_token*/
        load()->classs('wxapp.account');
        $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= '". $_W['uniacid']."'" );
        $accObj= new \WxappAccount( $account);
        $ACCESS_TOKEN = $accObj->getAccessToken( );
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" .$ACCESS_TOKEN;
        $ret = ihttp_post($url, json_encode(['code'=> $_GPC['code']]));
        $ret = json_decode($ret['content'], true);
        $phone_info = [];
        if($ret['errorCode']==0){
            //通过api接口获取手机号
            $phone_info = $ret['phone_info'];

        }
        $this->success('phone_info', $phone_info);

    }

    /**
     * 小程序的首页配置参数
     * @return void
     */
    public function option()
    {
        global $_W;
        $indexslides = KnscyBanner::where('status', 1)
            ->where('type_id', 0)
            ->field('id,title,thumb')
            ->order(Db::raw('sort=0,sort asc,id desc'))
            ->select()->each(function ($item, $key) {
                $item->image = get_full_url($item->thumb);
            })
            ->toArray();

        //导航菜单
        $navmenu = [
            [
                'thumb' => tomedia('/addons/kbwdl_nickscenery/public/images/icon-map.jpg'),
                'title' => '游玩指南',
                'open_url' => '/pages/paper/intro',
                'link_type' => 0,
            ],
            [
                'thumb' => tomedia('/addons/kbwdl_nickscenery/public/images/icon-coupon.jpg'),
                'title' => '年卡套餐',
                'open_url' => '/pages/card/card',
                'link_type' => 0,
            ],
            [
                'thumb' => tomedia('/addons/kbwdl_nickscenery/public/images/icon-card.jpg'),
                'title' => '领券中心',
                'open_url' => '/pages/card/redpack',
                'link_type' => 0,
            ],
            [
                'thumb' => tomedia('/addons/kbwdl_nickscenery/public/images/icon-che.jpg'),
                'title' => '停车缴费',
                'open_url' => '/pages/single/che',
                'link_type' => 0,
            ]
        ];
        //获取企业信息
        $company = sysconfig('company');
        if(!empty($company['company_logo'])){
            $company['company_logo'] = tomedia($company['company_logo']);

            $map_point  = CommonService::baidu_map_txmap($company['map_point']??'110.189648,25.240393');
            //地图标注
            $map = ['id'=>1,'latitude'=>'','longitude'=>'','title'=>$company['company_name']];
            if($map_point){
                $point = explode(",", $map_point);
                $map['latitude'] = $point[1] ??'110.189648';
                $map['longitude'] = $point[0] ??'25.240393';
            }
            $company['map_point'] = $map;
        }
        $this->success('success', [
            'indexslides' => $indexslides,
            'navmenu' => $navmenu,
            'company' => $company,
            'account' => $_W['account'],
            'user' => $this->userInfo, //返回当前用户信息
        ]);
    }

    /**
     * 必玩推荐
     */
    public function biwanPage()
    {
        $list = KnscyPages::where('status', 1)
            ->where('cate_id', KnscyPages::biwanxiangmu)
            ->select()->each(function ($item) {
                $item->cover = get_full_url($item->cover);
            });

        $this->success('success', $list);
    }

    /**
     * 通过单页分类获取一片内容
     * @return void
     */
    public function pageDetailsByCateId()
    {
        $cat_id= $this->request->post('cat_id');

        $data = KnscyPages::where('status', 1)
                ->where('cate_id', $cat_id)
                ->order(Db::raw('sort=0,sort asc,id desc'))
                ->find();
        if (empty($data)) {
            $this->success('暂无数据');
        }

        $data->content = img_alt($data->content);

        $this->success('success', $data);
    }

    public function singlePageDetails()
    {
        $id = $this->request->post('id');

        $data = KnscyPages::where('status', 1)->where('id', $id)->find();
        if (empty($data)) {
            $this->success('暂无数据');
        }
        $data->content = img_alt($data->content);

        $this->success('success', $data);
    }

    /**
     * 获取指定分类的页面
     */
    public function aboutPage()
    {
        $model = new KnscyPages();
        $cate = $model->getCategoryList();
        $cate = array_column($cate, null, 'id');

        $cate_ids = array_filter(array_keys($cate), function ($v, $k) {
            return ($v > 0 && $v !== 4);
        }, ARRAY_FILTER_USE_BOTH);

        $pages = [];
        $list = KnscyPages::where('status', 1)
            ->whereIn('cate_id', $cate_ids)
            ->field('id,cate_id,title,sub_title')
            ->order(Db::raw('sort=0,sort asc,id desc'))
            ->select()->each(function ($item) use (&$pages) {

                if(!isset($pages[$item['cate_id']])){
                    $pages[$item['cate_id']] = $item;
                }

            });
        $data = [];
        foreach ($cate as $k => $v) {
            $v['show_id'] = 0;
            if (isset($pages[$v['id']])) {
                $v['title'] = $pages[$v['id']]['title'];
                $v['show_id'] = $pages[$v['id']]['id'];
            }
            $data[$v['id']] = $v;
        }

        $this->success('success', $data);

    }

}